package me.shurufa.net;

import android.os.Build;
import android.text.TextUtils;

import java.util.ArrayList;
import java.util.Collections;

import cn.finalteam.okhttpfinal.HttpCycleContext;
import me.shurufa.MainApplication;
import me.shurufa.db.PersistenceUtils;
import me.shurufa.utils.Utils;

/**
 * Create by andy (https://github.com/andyxialm)
 * Create time: 16/5/12 08:54
 * Description : RequestParams
 */
public class RequestParams extends cn.finalteam.okhttpfinal.RequestParams {

    private static final String DEVICEID = "mid";
    private static final String PLATFORM = "platform";
    private static final String MODEL = "phone_model";

    private static final String OS = "os";
    private static final String VERSION = "app_version";
    private static final String SRF_AUTH = "srf_auth";

    private static final String SRF_KEY = "srf_key";
    private static final String TIMESTAMP = "timestamp";
    private static final String NONCE = "nonce";
    private static final String SIGNATURE = "signature";

    public RequestParams() {
        putGlobalParams();
    }

    public RequestParams(HttpCycleContext cycleContext) {
        super(cycleContext);
        putGlobalParams();
    }

    private void putGlobalParams() {
        long timestampInt = (System.currentTimeMillis() / 1000);
        String timestamp = String.valueOf(timestampInt);
        addFormDataPart(DEVICEID, Utils.getUniquePsuedoID()); // 设备ID
        addFormDataPart(PLATFORM, "android"); // 平台
        addFormDataPart(MODEL, TextUtils.isEmpty(Build.MODEL) ? "" : Build.MODEL);

        addFormDataPart(OS, Build.VERSION.RELEASE);
        addFormDataPart(VERSION, Utils.getVersionName(MainApplication.getInstance())); // 当前版本号
        addFormDataPart(TIMESTAMP, timestamp);

        addFormDataPart(NONCE, "shurufa_app");
        addFormDataPart(SIGNATURE, getSignature(timestamp));

        addFormDataPart(SRF_KEY, PersistenceUtils.getSrfKey());
        addFormDataPart(SRF_AUTH, PersistenceUtils.getSrfAuth());
    }

    /**
     * 获得签名
     * @param timestamp
     * @return
     */
    private static String getSignature(String timestamp) {
        ArrayList<String> dataList = new ArrayList<>();
        dataList.add(timestamp);
        dataList.add("app_api_shurufa_me");
        dataList.add("shurufa_app");
        dataList.add(Utils.getUniquePsuedoID());
        Collections.sort(dataList);

        StringBuilder signature = new StringBuilder();
        for (String s : dataList) {
            signature.append(s);
        }
        return Utils.SHA1(signature.toString());
    }
}
